<script lang="ts" setup>
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from "vue"
import { deleteTaskDataApi, getTableDataApi } from "@/api/task"
import { type TableData } from "@/api/task/types/task"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus } from "@element-plus/icons-vue"
import { useRouter } from "vue-router"
import { usePagination } from "@/hooks/usePagination"
import { taskStatusOptions, taskModeOptions, TabTypeEnum, TASK_MODE } from "@/constants/other-keys"

defineOptions({
  // 命名当前组件
  name: "GameTaskList"
})
let timer: number | null = null
const router = useRouter()
const loading = ref<boolean>(false)
const searchMore = ref<boolean>(false)
const taskStatusMap = computed<{ [propName: string]: string }>(() => {
  return taskStatusOptions.value.reduce((acc: { [propName: string]: string }, curr) => {
    acc[curr.value] = curr.name
    return acc
  }, {})
})
const taskModeMap = computed<{ [propName in TASK_MODE]: string }>(() => {
  return taskModeOptions.value.reduce(
    (acc, curr) => {
      acc[curr.value] = curr.name
      return acc
    },
    {} as { [propName in TASK_MODE]: string }
  )
})
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const handleSearchMore = () => {
  searchData.publish_time = undefined
  searchData.end_time = undefined
  searchMore.value = !searchMore.value
}
//#region 详情
const handleView = (row: TableData) => {
  router.push({ name: "GameTaskView", query: { id: row.task_id } })
}
//#endregion
//#region 增
const handleCreate = () => {
  router.push({ name: "GameTaskCreate" })
}
//#endregion
//#region 删
const handleDelete = (row: TableData) => {
  ElMessageBox.confirm(`正在删除任务：${row.task_name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTaskDataApi(row.task_id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
// const handleUpdate = (row: TableData) => {
//   router.push({ name: "GameTaskEdit", query: { id: row.task_id } })
// }
//#endregion

//#region 查
const tableData = ref<TableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  task_name: undefined,
  task_type: undefined,
  task_mode: undefined,
  task_status: undefined,
  publish_time: undefined,
  end_time: undefined
})
const justTableData = () => {
  getTableDataApi({
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    task_name: searchData.task_name || undefined,
    task_type: TabTypeEnum.DYNAMIC,
    task_mode: searchData.task_mode,
    task_status: searchData.task_status || undefined,
    publish_time: searchData.publish_time || undefined,
    end_time: searchData.end_time || undefined
  }).then(({ data }) => {
    tableData.value = data.page_info
    paginationData.total = data.total_count
  })
}
const getTableData = () => {
  loading.value = true
  getTableDataApi({
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    task_name: searchData.task_name || undefined,
    task_type: TabTypeEnum.DYNAMIC,
    task_mode: searchData.task_mode,
    task_status: searchData.task_status || undefined,
    publish_time: searchData.publish_time || undefined,
    end_time: searchData.end_time || undefined
  })
    .then(({ data }) => {
      tableData.value = data.page_info
      paginationData.total = data.total_count
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

onMounted(() => {
  timer = Number(setInterval(justTableData, 1000 * 60))
})
onBeforeUnmount(() => {
  timer && clearInterval(timer)
})
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="task_name" label="任务名称">
          <el-input v-model="searchData.task_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="task_mode" label="任务模式">
          <el-select v-model="searchData.task_mode" clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in taskModeOptions" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="task_status" label="任务状态">
          <el-select v-model="searchData.task_status" clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in taskStatusOptions" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button link type="primary" @click="handleSearchMore">{{ searchMore ? "收起" : "更多" }}</el-button>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-row v-if="searchMore">
          <el-form-item prop="publish_time" label="发布时间">
            <el-date-picker
              v-model="searchData.publish_time"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择"
            />
          </el-form-item>
          <el-form-item prop="end_time" label="截至时间">
            <el-date-picker v-model="searchData.end_time" value-format="YYYY-MM-DD" type="date" placeholder="请选择" />
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>
    <div class="toolbar-wrapper">
      <div>
        <el-button type="primary" :icon="CirclePlus" @click="handleCreate">新增任务</el-button>
      </div>
    </div>
    <el-row v-loading="loading" shadow="never" :gutter="20">
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="5" class="mb-5" v-for="(item, index) in tableData" :key="index">
        <el-card class="card-item" body-class="card-item body">
          <div class="card-header flex-between">
            <el-space class="flex-vc">
              <el-icon><Calendar /></el-icon>
              <el-text>{{ item.create_time }}</el-text>
            </el-space>
            <el-text>
              {{ taskStatusMap[item.task_status] }}
              <template v-if="item.task_status == 1">
                <el-divider direction="vertical" /> {{ item.task_process }}%
              </template>
            </el-text>
          </div>
          <div class="line-div">
            <div
              v-if="item.task_status == 1"
              class="line-div-color"
              :style="`width: ${item.task_process}%; background: '#409eff'`"
            />
            <div v-else-if="item.task_status == 2" class="line-div-color" style="width: 100%; background: #67c23a" />
          </div>
          <div class="card-body">
            <div class="flex-between relation">
              <el-space class="flex-vc">
                <el-tag type="primary">{{
                  taskModeMap[JSON.parse(item.task_param).task_config.mode as TASK_MODE]
                }}</el-tag>
                <el-text size="large" class="w-150px mb-2" truncated>
                  {{ item.task_name }}
                </el-text>
              </el-space>
              <el-space class="flex-vc card-operate">
                <el-link :underline="false" @click="handleView(item)">
                  <el-icon :size="18"><View /></el-icon>
                </el-link>
                <!-- <el-link :underline="false" @click="handleUpdate(item)">
                  <el-icon :size="18"><Edit /></el-icon>
                </el-link> -->
                <el-link :underline="false" @click="handleDelete(item)">
                  <el-icon :size="18"><Delete /></el-icon>
                </el-link>
              </el-space>
            </div>
            <p class="describe">
              <el-text size="large" type="info" line-clamp="2">
                {{ item.task_describe }}
              </el-text>
            </p>
          </div>
          <template #footer>
            <div class="card-footer flex-between">
              <el-space class="flex-vc">
                <el-icon><UserFilled /></el-icon>
                <el-text>{{ item.create_user.user_name }}</el-text>
              </el-space>
              <el-tag type="info" effect="plain">{{ item.create_user.user_position }}</el-tag>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
    <div class="pager-wrapper">
      <el-pagination
        background
        :layout="paginationData.layout"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :currentPage="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@/styles/custom.scss";
</style>
